<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    :width="width"
    :append-to-body="appendToBody"
    :draggable="draggable"
    :before-close="handleClose"
  >
    <el-upload
      class="upload-demo"
      drag
      :action="action"
      multiple
      :data="data"
      @on-success="onSuccess"
      @on-error="onError"
      @on-change="onChange"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">将文件放到这里或 <em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip">{{ fileType }} 文件大小应小于 500kb</div>
      </template>
    </el-upload>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="onCancel">{{ conCancel }}</el-button>
        <el-button type="primary" @click="onConfirm"> {{ confirmText }} </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { UploadFilled } from '@element-plus/icons-vue'

let dialogVisible = ref(false)
defineProps({
  title: {
    type: String,
    default: '系统提示'
  },
  width: {
    type: String,
    default: '500'
  },
  confirmText: {
    type: String,
    default: '确认'
  },
  conCancel: {
    type: String,
    default: '取消'
  },
  appendToBody: {
    type: Boolean,
    default: true
  },
  draggable: {
    type: Boolean,
    default: true
  },
  action: {
    //地址
    type: String,
    default: import.meta.env.VITE_APP_FILES_UPLOAD_URL
  },
  fileType: {
    type: String,
    default: 'xls'
  },
  data: {
    type: Object,
    default: () => {}
  }
})
const emit = defineEmits(['onUpload'])
const response = ref('')
interface UploadFile {
  file: string
}
//显示弹框
const show = () => {
  dialogVisible.value = true
}
//隐藏弹框
const hide = () => {
  dialogVisible.value = false
}
const handleClose = () => {
  hide()
}
const onConfirm = () => {
  hide()
  onUpload(response.value)
}
const onCancel = () => {
  hide()
}

//文件上传成功时的钩子
const onSuccess = (response: any) => {
  console.log(response, '===========onSuccess==========')
  response.value = response
}

//文件上传失败时的钩子
const onError = (response: any) => {
  console.log(response, '==========onError===========')
  response.value = response
}

//文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
const onChange = (uploadFile: UploadFile) => {
  console.log(uploadFile, '===========onChange==========')
}

//返回的数据
const onUpload = (response: any) => {
  emit('onUpload', response)
}

defineExpose({
  show,
  hide
})
</script>
